import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
import { SortConfig } from '../sort/api';
import { FilterConfig } from '../core/api';
import { PageConfig } from '../pagination/api';
import { TdComponent } from './td.component';
import { RowCheckFactor } from './interface';

@Injectable()
export class DatatableService {
  parentComponent;
  pageMap: PageConfig; // 分页器条件只会有一个
  sortMap = new Map<string, SortConfig>(); // 目前控制只有一个条件
  filterMap = new Map<string, FilterConfig>();

  checkboxChange$ = new Subject<RowCheckFactor>();
  rowComponentsMap = new Map<string, TdComponent>();

  constructor() {}

  clearSortState(): void {
    this.sortMap.clear();
  }

  clearFilterState(): void {
    this.filterMap.clear();
  }

  removePaginatorState(): void {
    this.pageMap = null;
  }

  getPaginatorState(): PageConfig {
    return this.pageMap;
  }

  getParentComponent(): any {
    return this.parentComponent;
  }

  clearRowComponents(): void {
    this.rowComponentsMap.clear();
  }

  getSortState(): Map<string, SortConfig> {
    return this.sortMap;
  }

  removeSortState(key: string): void {
    this.sortMap.delete(key);
  }

  /**
   * paginator
   */
  setPaginatorState(data: PageConfig): void {
    this.pageMap = data;
  }

  removeFilterState(key: string): void {
    this.filterMap.delete(key);
  }

  getFilterState(): Map<string, FilterConfig> {
    return this.filterMap;
  }

  /**
   * parent
   */
  setParentComponent(component): void {
    this.parentComponent = component;
  }

  removeRowComponent(key: string): void {
    this.rowComponentsMap.delete(key);
  }

  getRowComponents(): Map<string, TdComponent> {
    return this.rowComponentsMap;
  }

  /**
   * filter
   */
  setFilterState(data: FilterConfig): void {
    this.filterMap.set(data.key, data);
  }

  getCheckboxStream(): Observable<any> {
    return this.checkboxChange$.asObservable();
  }

  setCheckboxStream(source: RowCheckFactor): void {
    this.checkboxChange$.next(source);
  }

  /**
   * rowComponents
   */
  setRowComponents(key: string, value: TdComponent): void {
    this.rowComponentsMap.set(key, value);
  }

  /**
   * 更新分页组件选中项条数
   */
  updatePaginatorSelected(page: any, length: number): void {
    if (!page) {
      return;
    }
    page.setSelected(length);
  }

  /**
   * sort
   */
  setSortState(data: SortConfig): void {
    // sort 只支持一个条件
    this.sortMap = new Map<string, SortConfig>();
    this.sortMap.set(data.key, data);
  }
}
